import type { Next, Context } from 'koa';
import knex from '../utils/knex';
import _ from 'lodash';

/**
 * @api {get} /dict/retrieve 查询字典
 * @apiVersion 1.0.0
 * @apiDescription create by wuyanshen
 * @apiName retrieve
 * @apiGroup 字典管理
 *
 * @apiUse RequestPagingParam
 * @apiParam {String}     name       字典名称【非必填】
 * @apiParam {String}     type       字典类型【非必填】
 * @apiParam {String}     startTime  字典创建时间-开始【非必填】
 * @apiParam {String}     endTime    字典创建时间-结束【非必填】
 * @apiParam {String}     status     字典状态 (0:正常 1:停用)【非必填】
 *
 * @apiUse RequestHeader
 * @apiUse dictRetrieveSuccess
 * @apiUse RequestError
 */
async function retrieveAction(ctx: Context, next: Next) {
    const { page = 1, size = 10, name = '', type = '', status, startTime = '', endTime = '' } = ctx.query;
    const whereObj: Record<string, any> = {};
    if (name) {
        whereObj.name = ['like', `%${name}%`];
    }
    if (type) {
        whereObj.type = type;
    }
    if (status) {
        whereObj.status = status;
    }
    if (startTime && endTime) {
        whereObj.create_time = ['between', startTime, endTime];
    }
    try {
        const data = await knex('sys_dict')
            .where(whereObj)
            .offset(((page as number) - 1) * (size as number))
            .limit(size as number)
            .select();
        const count = await knex('sys_dict').where(whereObj).count();
        ctx.success(
            {
                data,
                count: Object.values(count[0])[0],
            },
            '查询成功',
        );
    } catch (e) {
        ctx.fail(500, '查询失败  ' + e);
    }
    return next();
}

/**
 * @api {post} /dict/add 新增字典
 * @apiVersion 1.0.0
 * @apiDescription create by wuyanshen
 * @apiName add
 * @apiGroup 字典管理
 *
 * @apiParam {String}  name      字典名称【必填】
 * @apiParam {String}  type      字典类型【必填】
 * @apiParam {String}  remark    备注【必填】
 * @apiParam {String}  status    字典状态 (0:正常 1:停用)【必填】
 *
 * @apiUse RequestHeader
 * @apiUse addSuccess
 * @apiUse RequestError
 */
async function addAction(ctx: Context, next: Next) {
    const { name = '', type = '', status, remark = '' } = ctx.request.body;
    try {
        await knex('sys_dict').insert({
            name: name,
            type: type,
            status: status,
            remark: remark,
        });
        ctx.success('', '新增成功');
    } catch (e) {
        ctx.fail(500, '新增失败  ' + e);
    }
    return next();
}

/**
 * @api {delete} /dict/delete 删除字典
 * @apiVersion 1.0.0
 * @apiDescription create by wuyanshen
 * @apiName delete
 * @apiGroup 字典管理
 *
 * @apiParam {int}     id    字典id【必填】
 * @apiParam {String}  type  字典类型【必填】
 *
 * @apiUse RequestHeader
 * @apiUse deleteSuccess
 * @apiUse RequestError
 */
async function deleteAction(ctx: Context, next: Next) {
    const { id, type } = ctx.request.body;
    try {
        const res = await knex('sys_dict_item').where({ type: type }).first();
        if (!_.isEmpty(res)) {
            ctx.fail(400, '该字典已分配字典项目不允许删除');
            return next();
        }
        await knex('sys_dict').where({ id: id }).delete();
        ctx.success('', '删除成功');
    } catch (e) {
        ctx.fail(500, '删除失败  ' + e);
    }
    return next();
}

/**
 * @api {put} /dict/update 修改字典
 * @apiVersion 1.0.0
 * @apiDescription create by wuyanshen
 * @apiName update
 * @apiGroup 字典管理
 *
 * @apiParam {int}     id        字典id【必填】
 * @apiParam {String}  name      字典名称【必填】
 * @apiParam {String}  type      字典类型【必填】
 * @apiParam {String}  remark    备注【必填】
 * @apiParam {String}  status    字典状态 (0:正常 1:停用)【必填】
 *
 * @apiUse RequestHeader
 * @apiUse updateSuccess
 * @apiUse RequestError
 */
async function updateAction(ctx: Context, next: Next) {
    const { id, name = '', type = '', status, remark = '' } = ctx.request.body;
    try {
        await knex('sys_dict').where('id', id).update({
            name: name,
            type: type,
            status: status,
            remark: remark,
        });
        ctx.success('', '修改成功');
    } catch (e) {
        ctx.fail(500, '修改失败  ' + e);
    }
    return next();
}

/**
 * @api {get} /dict/checkDictType 检查字典类型是否已存在
 * @apiVersion 1.0.0
 * @apiDescription create by wuyanshen
 * @apiName checkDictType
 * @apiGroup 字典管理
 *
 * @apiUse RequestPagingParam
 * @apiParam {String}     type       字典类型【非必填】
 *
 * @apiUse RequestHeader
 * @apiUse dictCheckDictTypeSuccess
 * @apiUse RequestError
 */
async function checkDictTypeAction(ctx: Context, next: Next) {
    const { type = '' } = ctx.query;
    try {
        const res = await knex('sys_dict').where({ type: type }).first();
        if (_.isEmpty(res)) {
            ctx.success(0, '字典类型可用');
        } else {
            ctx.success(1, '字典类型已存在');
        }
    } catch (e) {
        ctx.fail(500, '检查失败  ' + e);
    }
    return next();
}

/**
 * @api {get} /dict/list 查询字典列表
 * @apiVersion 1.0.0
 * @apiDescription create by wuyanshen -> 字典项页面下拉框
 * @apiName list
 * @apiGroup 字典管理
 *
 * @apiUse RequestHeader
 * @apiUse dictListSuccess
 * @apiUse RequestError
 */
async function listAction(ctx: Context, next: Next) {
    try {
        const res = await knex('sys_dict').select();
        ctx.success(res, '查询成功');
    } catch (e) {
        ctx.fail(500, '查询失败  ' + e);
    }
    return next();
}

/**
 * @api {get} /dict/info 查询字典详情
 * @apiVersion 1.0.0
 * @apiDescription create by wuyanshen -> 回显字典项下拉框
 * @apiName info
 * @apiGroup 字典管理
 *
 * @apiUse RequestPagingParam
 * @apiParam {int}     id       字典id【必填】
 *
 * @apiUse RequestHeader
 * @apiUse dictInfoSuccess
 * @apiUse RequestError
 */
async function infoAction(ctx: Context, next: Next) {
    const { id } = ctx.query;
    try {
        const res = await knex('sys_dict').where({ id: id }).first();
        ctx.success(res, '查询成功');
    } catch (e) {
        ctx.fail(500, '查询失败  ' + e);
    }
    return next();
}

const dictController = {
    retrieveAction,
    addAction,
    listAction,
    infoAction,
    checkDictTypeAction,
    updateAction,
    deleteAction,
};

export default dictController;
